﻿using ConsoleOldToNew.ORM;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleOldToNew
{
    class DataSend
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DataSend));

      
        private string TranPWD = "";
        private SocketClient objSocketClient;
        private string str服务器IP;
        private int int服务器端口;
        private int int数据发送之间间隔;
        public DataSend(string TranPWD, SocketClient objSocketClient, string str服务器IP, int int服务器端口, int int数据发送之间间隔)
        {
            this.TranPWD = TranPWD;
            this.objSocketClient = objSocketClient;
            this.str服务器IP = str服务器IP;
            this.int服务器端口 = int服务器端口;
            this.int数据发送之间间隔 = int数据发送之间间隔;
        }


        /// <summary>
        /// SOCKET发送数据
        /// </summary>
        public void Socket_Data_Send()
        {
            try
            {
                #region 原来的
                using (DB_TotalControl_SX context = new DB_TotalControl_SX())
                {
                    DateTime dtNow = DateTime.Now;//当前时间
                    var t_OldNews = context.T_OldNew.ToList();

                    List<Envi_PS_Waste_Water_Let_Port> letPorts = context.Envi_PS_Waste_Water_Let_Port.ToList();//排口表
                    List<Envi_Valve_Monitor> ValveStates = context.Envi_Valve_Monitor.ToList();

                    foreach (T_OldNew objT_OldNew in t_OldNews)
                    {
                        Envi_PS_Waste_Water_Let_Port objLetPort = letPorts.Where(t => t.Data_Collection_Instrument_SN == objT_OldNew.MN).FirstOrDefault();
                        if (objLetPort != null)
                        {
                            if (objSocketClient.Data_Trans_Conn(str服务器IP, int服务器端口))//
                            {
                                try
                                {
                                    string strMN = objLetPort.Data_Collection_Instrument_SN;
                                    string strOnlineNum = objLetPort.online_inspect_Number;
                                    string strLet_Port_ID = objLetPort.ID.ToString();
                                    MainProtocol obj心跳包MainProtocol = new MainProtocol();
                                    obj心跳包MainProtocol.StrST = "28";
                                    obj心跳包MainProtocol.StrTP = "1";
                                    obj心跳包MainProtocol.StrPW = TranPWD;
                                    obj心跳包MainProtocol.StrMN = strMN;
                                    obj心跳包MainProtocol.StrDATATIME = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    string strHeartBeat = ZheJiangProtocol_Data.GetProtocolDataInfo(obj心跳包MainProtocol, null);

                                    if (objSocketClient.Data_Send(Encoding.Default.GetBytes("##" + strHeartBeat + "\r\n"), 5000))
                                    {
                                        Log.Info("发送心跳包：" + strHeartBeat);
                                    }
                                    Thread.Sleep(int数据发送之间间隔);

                                    Envi_Valve_Monitor objEnvi_Valve_Monitor = ValveStates.Where(t => t.Let_Port == objLetPort.ID).FirstOrDefault();//阀门监控
                                    if (objEnvi_Valve_Monitor != null)
                                    {
                                        if (objEnvi_Valve_Monitor.Get_Time.HasValue && objEnvi_Valve_Monitor.Valve_State != null)
                                        {
                                            string valveState = objEnvi_Valve_Monitor.Valve_State;//阀门状态
                                            if (valveState != null && valveState.Trim() != "")
                                            {
                                                try
                                                {
                                                    if (int.Parse(valveState) < 0)
                                                    {
                                                        valveState = "-1";
                                                    }
                                                    if (int.Parse(valveState) > 100)
                                                    {
                                                        valveState = "100";
                                                    }
                                                }
                                                catch
                                                { }

                                            }
                                            else
                                            {
                                                valveState = "-1";
                                            }

                                            string[] str阀门监控Datas = new string[2];

                                            MainProtocol obj阀门监控MainProtocol = new MainProtocol();
                                            obj阀门监控MainProtocol.StrST = "24";
                                            obj阀门监控MainProtocol.StrTP = "1";
                                            obj阀门监控MainProtocol.StrPW = TranPWD;
                                            obj阀门监控MainProtocol.StrMN = strMN;
                                            obj阀门监控MainProtocol.StrDATATIME = DateTime.Now.ToString("yyyyMMddHHmmss");
                                            obj阀门监控MainProtocol.StrControllerId = strMN;
                                            obj阀门监控MainProtocol.StrDate = objEnvi_Valve_Monitor.Get_Time.Value.ToString("yyyyMMddHHmmss");

                                            str阀门监控Datas[0] = "0650=1";
                                            str阀门监控Datas[1] = "0651=" + valveState;
                                            string strSend = ZheJiangProtocol_Data.GetProtocolDataInfo(obj阀门监控MainProtocol, str阀门监控Datas);

                                            if (objSocketClient.Data_Send(Encoding.Default.GetBytes(SendInfo.GetSendInfo(strSend)), 5000))
                                            {
                                                Log.Info("发送阀门状态：" + strSend);
                                            }
                                            Thread.Sleep(int数据发送之间间隔);
                                        }
                                    }
                                    if (dtNow.Minute > 40 && objT_OldNew.时间.HasValue)
                                    {
                                        bool isNormal = true;
                                        List<Envi_PS_Waste_Water_Flow_Hour_Correct_Data> hours = null;
                                        DateTime dtOldNewTime = objT_OldNew.时间.Value;

                                        if (dtNow.Hour == 3 || dtNow.Hour == 4)
                                        {
                                            DateTime dtYesterday = dtNow.AddDays(-1);
                                            hours = context.Envi_PS_Waste_Water_Flow_Hour_Correct_Data.Where(t => t.Let_Port_ID == strLet_Port_ID && t.Date_Time.Value.Year == dtYesterday.Year && t.Date_Time.Value.Month == dtYesterday.Month && t.Date_Time.Value.Day == dtYesterday.Day).OrderBy(t => t.Date_Time).ToList();


                                            DateTime dtBegin = new DateTime(dtYesterday.Year, dtYesterday.Month, dtYesterday.Day, 0, 0, 0);
                                            DateTime dtEnd = new DateTime(dtYesterday.Year, dtYesterday.Month, dtYesterday.Day, 23, 0, 0);

                                            hours = GetAllHours(hours, dtBegin, dtEnd);
                                            isNormal = false;
                                        }
                                        else
                                        {
                                            hours = context.Envi_PS_Waste_Water_Flow_Hour_Correct_Data.Where(t => t.Let_Port_ID == strLet_Port_ID && t.Date_Time > dtOldNewTime).OrderBy(t => t.Date_Time).ToList();
                                            if (dtNow.Year == dtOldNewTime.Year && dtNow.Month == dtOldNewTime.Month && dtNow.Day > dtOldNewTime.Day)
                                            {
                                                DateTime dtBegin = new DateTime(dtOldNewTime.Year, dtOldNewTime.Month, dtOldNewTime.Day, dtOldNewTime.Hour, 0, 0);
                                                DateTime dtE = dtNow.AddHours(-2);
                                                DateTime dtEnd = new DateTime(dtE.Year, dtE.Month, dtE.Day, dtE.Hour, 0, 0);
                                                hours = GetAllHours(hours, dtBegin, dtEnd);
                                            }
                                        }

                                        int num = 0;
                                        foreach (Envi_PS_Waste_Water_Flow_Hour_Correct_Data obj小时数据 in hours)
                                        {
                                            if (num == hours.Count() - 1 && isNormal)
                                            {
                                                break;
                                            }
                                            if (obj小时数据.Date_Time.HasValue)
                                            {
                                                MainProtocol obj小时数据MainProtocol = new MainProtocol();
                                                obj小时数据MainProtocol.StrST = "17";
                                                obj小时数据MainProtocol.StrTP = "1";
                                                obj小时数据MainProtocol.StrPW = TranPWD;
                                                obj小时数据MainProtocol.StrMN = strMN;
                                                obj小时数据MainProtocol.StrDATATIME = DateTime.Now.ToString("yyyyMMddHHmmss");
                                                obj小时数据MainProtocol.StrControllerId = strMN;
                                                obj小时数据MainProtocol.StrDate = obj小时数据.Date_Time.Value.ToString("yyyyMMddHHmmss");


                                                string[] str小时数据Datas = new string[6];
                                                str小时数据Datas[0] = "0101=" + strOnlineNum;//2015-10-27严加

                                                //  string strFlow=(obj小时数据.Time_Flow.HasValue ? obj小时数据.Time_Flow.Value.ToString() : "");
                                                str小时数据Datas[1] = "5450=" + (obj小时数据.Time_Flow.HasValue ? obj小时数据.Time_Flow.Value.ToString() : "0");

                                                //  string strAvgCod=(obj小时数据.AVG_COD.HasValue ? obj小时数据.AVG_COD.Value.ToString() : "");
                                                //  string strAvgAn=(obj小时数据.AVG_AN.HasValue ? obj小时数据.AVG_AN.Value.ToString() : "");
                                                str小时数据Datas[2] = "5451=" + (obj小时数据.AVG_COD.HasValue ? obj小时数据.AVG_COD.Value.ToString() : "0");
                                                str小时数据Datas[3] = "5452=" + (obj小时数据.AVG_AN.HasValue ? obj小时数据.AVG_AN.Value.ToString() : "0");

                                                string strCouCod = "0";
                                                if (obj小时数据.Time_Flow.HasValue && obj小时数据.AVG_COD.HasValue)
                                                {
                                                    strCouCod = Math.Round(obj小时数据.Time_Flow.Value * obj小时数据.AVG_COD.Value, 2).ToString();
                                                }

                                                string strCouAn = "0";
                                                if (obj小时数据.Time_Flow.HasValue && obj小时数据.AVG_AN.HasValue)
                                                {
                                                    strCouAn = Math.Round(obj小时数据.Time_Flow.Value * obj小时数据.AVG_AN.Value, 2).ToString();
                                                }

                                                str小时数据Datas[4] = "5453=" + strCouCod;
                                                str小时数据Datas[5] = "5454=" + strCouAn;



                                                string strSend = ZheJiangProtocol_Data.GetProtocolDataInfo(obj小时数据MainProtocol, str小时数据Datas);

                                                if (objSocketClient.Data_Send(Encoding.Default.GetBytes(SendInfo.GetSendInfo(strSend)), 5000))//如果发送成功
                                                {
                                                    if (isNormal)
                                                    {
                                                        objT_OldNew.时间 = obj小时数据.Date_Time;
                                                    }
                                                    Log.Info("发送小时数据：" + strSend);
                                                }
                                                Thread.Sleep(int数据发送之间间隔);
                                                if (isNormal || (num < 2 && !isNormal))
                                                {
                                                    Day_Data_Send_Dispose(context, strLet_Port_ID, strMN, obj小时数据.Date_Time.Value);
                                                }
                                                Thread.Sleep(int数据发送之间间隔);
                                                if (isNormal || (num < 2 && !isNormal))
                                                {
                                                    Month_Data_Send_Dispose(context, strLet_Port_ID, strMN, obj小时数据.Date_Time.Value);
                                                }
                                                Thread.Sleep(int数据发送之间间隔);
                                            }
                                            num++;
                                        }
                                    }
                                    context.SaveChanges();
                                }
                                catch (Exception ex1)
                                {
                                    Log.Error(ex1);
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }



        private void Day_Data_Send_Dispose(DB_TotalControl_SX context, string strLet_Port_ID, string strMN, DateTime dtHour)
        {
            List<Envi_PS_Waste_Water_Flow_Hour_Correct_Data> days = context.Envi_PS_Waste_Water_Flow_Hour_Correct_Data.Where(t => t.Let_Port_ID == strLet_Port_ID && t.Date_Time.Value.Year == dtHour.Year && t.Date_Time.Value.Month == dtHour.Month && t.Date_Time.Value.Day == dtHour.Day).ToList();
            decimal flowZ = 0;
            decimal codZ = 0;
            decimal anZ = 0;
            foreach (Envi_PS_Waste_Water_Flow_Hour_Correct_Data i in days)
            {
                if (i.Time_Flow.HasValue)
                {
                    flowZ = flowZ + i.Time_Flow.Value;
                }

                if (i.Time_Flow.HasValue && i.AVG_COD.HasValue)
                {
                    codZ = codZ + i.Time_Flow.Value * i.AVG_COD.Value;
                }

                if (i.Time_Flow.HasValue && i.AVG_AN.HasValue)
                {
                    anZ = anZ + i.Time_Flow.Value * i.AVG_AN.Value;
                }
            }

            MainProtocol obj日数据MainProtocol = new MainProtocol();
            obj日数据MainProtocol.StrST = "16";
            obj日数据MainProtocol.StrTP = "1";
            obj日数据MainProtocol.StrPW = TranPWD;
            obj日数据MainProtocol.StrMN = strMN;
            obj日数据MainProtocol.StrDATATIME = DateTime.Now.ToString("yyyyMMddHHmmss");
            obj日数据MainProtocol.StrControllerId = strMN;
            obj日数据MainProtocol.StrDate = dtHour.ToString("yyyyMMddHHmmss");

            string[] str日数据Datas = new string[3];
            str日数据Datas[0] = "5350=" + flowZ.ToString();
            str日数据Datas[1] = "5351=" + codZ.ToString();
            str日数据Datas[2] = "5352=" + anZ.ToString();

            string strSend = ZheJiangProtocol_Data.GetProtocolDataInfo(obj日数据MainProtocol, str日数据Datas);

            if (objSocketClient.Data_Send(Encoding.Default.GetBytes(SendInfo.GetSendInfo(strSend)), 5000))
            {
                Log.Info("发送日数据：" + strSend);
            }


        }



        private void Month_Data_Send_Dispose(DB_TotalControl_SX context, string strLetPortID, string strMN, DateTime dtHour)
        {
            string strMonth = dtHour.Year.ToString() + "-" + dtHour.Month.ToString().PadLeft(2, '0');
            Envi_PS_Waste_Water_Flow_Month_Data obj月数据 = context.Envi_PS_Waste_Water_Flow_Month_Data.Where(t => t.Let_Port_ID == strLetPortID && t.Month == strMonth).FirstOrDefault();
            if (obj月数据 != null && obj月数据.Month.Length == 7)
            {
                string year = dtHour.Year.ToString();
                string month = dtHour.Month.ToString().PadLeft(2, '0');

                MainProtocol obj月数据MainProtocol = new MainProtocol();
                obj月数据MainProtocol.StrST = "15";
                obj月数据MainProtocol.StrTP = "1";
                obj月数据MainProtocol.StrPW = TranPWD;
                obj月数据MainProtocol.StrMN = strMN;
                obj月数据MainProtocol.StrDATATIME = DateTime.Now.ToString("yyyyMMddHHmmss");
                obj月数据MainProtocol.StrControllerId = strMN;
                obj月数据MainProtocol.StrDate = dtHour.ToString("yyyyMMddHHmmss");



                string[] str月数据Datas = new string[5];
                str月数据Datas[0] = "0004=" + year;
                str月数据Datas[1] = "0005=" + month;
                str月数据Datas[2] = "5306=" + (obj月数据.Month_Flow.HasValue ? obj月数据.Month_Flow.Value.ToString() : "0");
                str月数据Datas[3] = "5307=" + (obj月数据.COD_Month_Measure.HasValue ? (obj月数据.COD_Month_Measure.Value * 1000).ToString() : "0");//之后查下换算率
                str月数据Datas[4] = "5308=" + (obj月数据.AN_Month_Measure.HasValue ? (obj月数据.AN_Month_Measure.Value * 1000).ToString() : "0");


                string strSend = ZheJiangProtocol_Data.GetProtocolDataInfo(obj月数据MainProtocol, str月数据Datas);


                if (objSocketClient.Data_Send(Encoding.Default.GetBytes(SendInfo.GetSendInfo(strSend)), 5000))
                {

                    Log.Info("发送月数据：" + strSend);
                }

            }

        }




        private List<Envi_PS_Waste_Water_Flow_Hour_Correct_Data> GetAllHours(List<Envi_PS_Waste_Water_Flow_Hour_Correct_Data> hours, DateTime dtBegin, DateTime dtEnd)
        {
            //DateTime dtBegin = new DateTime(bDateTime.Year, bDateTime.Month, bDateTime.Day, bDateTime.Hour, 0, 0);
            //DateTime dtEnd = new DateTime(eDateTime.Year, eDateTime.Month, eDateTime.Day, eDateTime.Hour, 0, 0);
            TimeSpan timeSpan = new TimeSpan(0, 1, 0, 0);


            var listExistTime = hours.Select(t => t.Date_Time).ToList();//已存在的时间
            for (DateTime dtHourAll = dtBegin; dtHourAll <= dtEnd; dtHourAll += timeSpan)
            {
                bool isExist = false;
                foreach (DateTime dtExist in listExistTime)
                {
                    if (dtHourAll == dtExist)
                    {
                        isExist = true;
                        break;
                    }
                }
                if (!isExist)
                {
                    Envi_PS_Waste_Water_Flow_Hour_Correct_Data objLostHour = new Envi_PS_Waste_Water_Flow_Hour_Correct_Data();
                    objLostHour.Date_Time = dtHourAll;
                    objLostHour.Time_Flow = 0;
                    objLostHour.AVG_COD = 0;
                    objLostHour.AVG_AN = 0;
                    objLostHour.COD_Time_Measure = 0;
                    objLostHour.AN_Time_Measure = 0;
                    hours.Add(objLostHour);
                }

            }



            hours = hours.OrderBy(t => t.Date_Time).ToList();

            return hours;

        }



    }
}
